package com.hadluo.qq.client.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.client.model.UserInfo;
import com.hadluo.qq.client.utils.HttpClient;

public class ProfileDialog extends JDialog {
    private UserInfo userInfo;
    private JTextField nicknameField;
    private JTextField avatarField;
    private JButton saveButton;
    private JButton cancelButton;
    private JLabel avatarPreview;
    private ProfileUpdateListener updateListener;

    public interface ProfileUpdateListener {
        void onProfileUpdated(UserInfo updatedUserInfo);
    }


    public ProfileDialog(Frame owner, UserInfo userInfo , ProfileUpdateListener updateListener) {
        super(owner, "个人资料", true);
        this.userInfo = userInfo;
        this.updateListener = updateListener;
        initComponents();
        loadUserInfo();
        setLocationRelativeTo(owner);
    }

    private void initComponents() {
        setLayout(new BorderLayout());

        // 创建主面板，添加边距
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // QQ号（只读）
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("QQ号："), gbc);

        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField qqNumberField = new JTextField(userInfo.getQqNumber());
        qqNumberField.setEditable(false);
        formPanel.add(qqNumberField, gbc);

        // 昵称
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0;
        formPanel.add(new JLabel("昵称："), gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        nicknameField = new JTextField(20);
        formPanel.add(nicknameField, gbc);

        // 头像选择和预览
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0;
        formPanel.add(new JLabel("头像："), gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel avatarPanel = new JPanel(new BorderLayout(10, 0));
        avatarPanel.setBackground(mainPanel.getBackground());

        avatarField = new JTextField(20);
        avatarField.setEditable(false);
        avatarField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent e) { updateAvatarPreview(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e) { updateAvatarPreview(); }
            public void insertUpdate(javax.swing.event.DocumentEvent e) { updateAvatarPreview(); }
        });

        JButton chooseAvatarButton = new JButton("选择图片");
        chooseAvatarButton.addActionListener(e -> handleChooseAvatar());

        avatarPanel.add(avatarField, BorderLayout.CENTER);
        avatarPanel.add(chooseAvatarButton, BorderLayout.EAST);
        formPanel.add(avatarPanel, gbc);

        // 头像预览
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(15, 10, 10, 10);
        avatarPreview = new JLabel();
        avatarPreview.setPreferredSize(new Dimension(100, 100));
        avatarPreview.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        avatarPreview.setHorizontalAlignment(JLabel.CENTER);
        formPanel.add(avatarPreview, gbc);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        add(mainPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");

        saveButton.addActionListener(e -> saveProfile());
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 设置对话框大小
        setSize(500, 400);
        setMinimumSize(new Dimension(400, 350));
    }

    private void loadUserInfo() {
        nicknameField.setText(userInfo.getNickname());
        avatarField.setText(userInfo.getAvatar());
        updateAvatarPreview();
    }

    private void handleChooseAvatar() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter(
                "图片文件", "jpg", "jpeg", "png", "gif"));

        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                // 准备上传文件
                java.io.File file = fileChooser.getSelectedFile();
                String boundary = Long.toHexString(System.currentTimeMillis());

                // 创建连接
                URL url = new URL("http://localhost:8080/api/file/upload");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                try (OutputStream os = conn.getOutputStream();
                     java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file)) {

                    // 写入文件数据
                    byte[] boundary_bytes = ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
                    byte[] content_disposition = ("Content-Disposition: form-data; name=\"file\"; filename=\"" +
                            file.getName() + "\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8);

                    os.write(boundary_bytes);
                    os.write(content_disposition);

                    // 写入文件内容
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }

                    // 写入结束标记
                    os.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
                }

                // 处理响应
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        // 解析响应获取URL
                        JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                        String fileUrl = jsonResponse.getString("url");
                        // 更新头像字段和预览
                        avatarField.setText(fileUrl);
                        updateAvatarPreview();

                        JOptionPane.showMessageDialog(this,
                                "头像上传成功",
                                "成功",
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                } else {
                    throw new Exception("文件上传失败: " + responseCode);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this,
                        "上传头像失败: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void updateAvatarPreview() {
        String avatarUrl = avatarField.getText().trim();
        if (!avatarUrl.isEmpty()) {
            try {
                // 如果URL不是以http开头，添加服务器地址
                if (!avatarUrl.startsWith("http")) {
                    avatarUrl = "http://localhost:8080" + avatarUrl;
                }
                // 尝试加载头像图片
                ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                Image image = imageIcon.getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH);
                avatarPreview.setIcon(new ImageIcon(image));
                avatarPreview.setText("");
            } catch (Exception e) {
                // 加载失败时显示昵称首字母
                String nickname = nicknameField.getText().trim();
                String initial = nickname.isEmpty() ? "?" : nickname.substring(0, 1).toUpperCase();
                avatarPreview.setIcon(null);
                avatarPreview.setText(initial);
                avatarPreview.setFont(new Font("Arial", Font.BOLD, 36));
            }
        } else {
            // URL为空时显示昵称首字母
            String nickname = nicknameField.getText().trim();
            String initial = nickname.isEmpty() ? "?" : nickname.substring(0, 1).toUpperCase();
            avatarPreview.setIcon(null);
            avatarPreview.setText(initial);
            avatarPreview.setFont(new Font("Arial", Font.BOLD, 36));
        }
    }

    private void saveProfile() {
        String newNickname = nicknameField.getText().trim();
        String newAvatar = avatarField.getText().trim();

        if (newNickname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "昵称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            // 调用后端API更新个人资料
            boolean success = HttpClient.updateProfile(userInfo.getQqNumber(), newNickname, newAvatar);
            if (success) {
                // 更新本地用户信息
                userInfo.setNickname(newNickname);
                userInfo.setAvatar(newAvatar);
                // 通知监听器资料已更新
                if (updateListener != null) {
                    updateListener.onProfileUpdated(userInfo);
                }
                JOptionPane.showMessageDialog(this, "个人资料更新成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "更新失败，请稍后重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "更新失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}